package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.AuthDto;
import com.heima.user.dto.WmUser;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.feign.MediaFeign;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import com.sun.org.apache.regexp.internal.RE;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author zsk
 * @since 2022-04-11
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    /**
     * 用户认证模块显示
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listByStatus(AuthDto dto) {

        //构建分页条件
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();

        //判断状态是否存在
        if (dto.getStatus() != null) {
            //构建查询条件
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        //查询
        Page<ApUserRealname> page1 = this.page(page, wrapper);
        //构建返回条件
        PageResponseResult<List<ApUserRealname>> result = new PageResponseResult<>(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());

        //返回结果
        return result;
    }

    @Autowired
    private IApUserService userService;

    /**
     * 用户审核
     *
     * @param dto
     * @param type
     * @return
     */
    @GlobalTransactional
    @Override
    public ResponseResult auth(AuthDto dto, int type) {

        //查询用户认证表中信息
        ApUserRealname realname = this.getById(dto.getId());

        if (type == 0) {
            //代表驳回审核请求
            realname.setStatus(2);//2为审核失败，驳回
            realname.setReason(dto.getReason());//驳回理由
            //修改认证表中信息
            this.updateById(realname);
//            int i = 1 / 0;//代表事务会回滚
        } else {//代表审核通过

            //查询用户注册表中信息
            ApUser apUser = userService.getById(realname.getUserId());

            //创建自媒体账号信息
            WmUser wmUser = createWmUser(apUser);
            if (wmUser != null) {
                //创建作者
                ApAuthor apAuthor = createApAuthor(apUser, wmUser.getId());
                if (apAuthor != null) {//代表作者创建成功
                    //将作者id更新到wmuser表中
                    wmUser.setApAuthorId(apAuthor.getId());
                    //远程调用MediaFegin修改
                    mediaFeign.updateWmUser(wmUser);
                }

                //修改认证表中的状态为9
                realname.setStatus(9);
                this.updateById(realname);

                //修改用户注册表中的flag为1（自媒体人）
                apUser.setFlag(1);
                userService.updateById(apUser);
            }
        }

        //返回结果
        return ResponseResult.okResult();
    }

    @Autowired
    private ArticleFeign articleFeign;

    /**
     * 创建作者
     *
     * @param apUser
     * @param wmUserId:是wmuser表中的主键id
     * @return
     */
    private ApAuthor createApAuthor(ApUser apUser, Integer wmUserId) {
        ApAuthor author = new ApAuthor();
        //补全参数
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setWmUserId(wmUserId);

        //远程调用ApAuthorFegin保存
        ResponseResult<ApAuthor> apAuthorResponseResult = articleFeign.saveAuthor(author);
        //如果成功创建
        if (apAuthorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            //返回ApAuthor对象
            ApAuthor apAuthor = apAuthorResponseResult.getData();
            return apAuthor;
        }
        //错误或者没有创建
        return null;

    }

    @Autowired
    private MediaFeign mediaFeign;

    /**
     * 创建自媒体用户信息
     *
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //创建对象
        WmUser wmUser = new WmUser();

        //使用工具类自动匹配
        BeanUtils.copyProperties(apUser, wmUser);
        //补全其他参数
        wmUser.setId(null);//主键设置为null
        wmUser.setApUserId(apUser.getId());//wm的apuserId为apuser的主键id
        wmUser.setNickname(apUser.getName());//设置昵称
        wmUser.setStatus(9);//状态设置为9（正常可用）
        wmUser.setType(0);//0为个人账号
        //远程调用Mediafeign保存
        ResponseResult<WmUser> wmUserResponseResult = mediaFeign.saveWmUser(wmUser);
        //如果操作成功
        if (wmUserResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            //返回Wmuser对象
            WmUser user = wmUserResponseResult.getData();
            return user;
        }

        //操作失败,返回null
        return null;

    }
}
